﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/

using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using SupperTreeSample.Shared.Data;
using System.Xml.Linq;

namespace SupperTreeSample.Shared.Components;

public abstract class FoodNodeBase : ComponentBase, IAsyncDisposable
{
    /// <summary>
    /// 
    /// </summary>
    [Inject]
    [NotNull]
    protected IJSRuntime? JSRuntime { get; set; }

    /// <summary>
    /// 
    /// </summary>
    protected IJSObjectReference? Module { get; set; }

    /// <summary>
    /// 获得/设置 FoodNodeItem 小箭头样式
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    protected static string? GetCaretClassString(FoodNodeItem item) => CssBuilder.Default("fa fa-caret-right")
        .AddClass("fa-rotate-90", !item.IsCollapsed)
        .Build();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            Module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/SupperTreeSample.Shared/js/food.js");
        }
    }

    protected virtual ElementReference GetElement() => default;

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected async Task Toggle(int index, FoodNodeItem item)
    {
        if (Module is not null)
        {
            item.IsCollapsed = !item.IsCollapsed;
            var el = GetElement();
            if (el.Context != null)
            {
                await Module.InvokeVoidAsync("toggle", el, index, item.IsCollapsed);
            }
        }
    }

    /// <summary>
    /// 展开或者收缩所有节点功能
    /// </summary>
    /// <param name="collapse">为真时全部收缩 为假时全部展开</param>
    /// <returns></returns>
    public async Task ToggleAll(bool collapse, string level = "day")
    {
        if (Module is not null)
        {
            var el = GetElement();
            if (el.Context != null)
            {
                await Module.InvokeVoidAsync("toggle_all", el, collapse, level);
            }
        }
    }

    protected virtual async ValueTask DisposeAsync(bool disposing)
    {
        if (disposing)
        {
            if (Module is not null)
            {
                await Module.DisposeAsync();
            }
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public async ValueTask DisposeAsync()
    {
        await DisposeAsync(true);
        GC.SuppressFinalize(this);
    }
}
